<template>
  <view class="container w-[750rpx] mx-auto">
    <!-- 顶部区域 -->
    <view
      class="header bg-gradient-to-r from-[#2196F3] to-[#1976D2] text-white p-[30rpx_40rpx_20rpx] sticky top-0 z-100 shadow-[0_4rpx_30rpx_rgba(33,150,243,0.3)] rounded-b-[40rpx]"
    >
      <view class="top-bar flex justify-between items-center">
        <view class="location flex items-center text-[28rpx] font-medium" @click="handleLocation">
          <icon-font name="map-marker-alt" class="mr-[10rpx]" />
            <view class="flex items-center">
              <IconFont name="location" size="14" class="mr-[10rpx]"></IconFont>
              <text>{{ locationObj.address_component?.province || '未授权定位'  }} · {{ locationObj.address_component?.city || '未授权定位' }}</text>
            </view>
        </view>
      </view>
    </view>

    <!-- 搜索区域 -->
    <!-- <view class="search-container px-[30rpx] mt-[30rpx]">
      <SearchView />
    </view> -->

    <!-- 广告轮播 -->
    <view
      class="banner mx-[30rpx] mt-[30rpx] rounded-[40rpx] overflow-hidden h-[320rpx] relative shadow-[0_12rpx_30rpx_rgba(33,150,243,0.2)]"
    >
      <nut-swiper 
      :init-page="1"
      :auto-play="3000"
      pagination-visible
      pagination-color="#426543"
      pagination-unselected-color="#808080"
      class="w-full h-full">
        <nut-swiper-item v-for="(item, index) in bannerList" :key="index" class="w-full h-full">
          <view class="w-full h-full relative">
            <image 
              :src="item.imgUrl" 
              class="w-full h-full" 
              mode="aspectFill"
              @error="(e) => handleImageError(e, index)"
              @load="(e) => handleImageLoad(e, index)"
            />
            <!-- 加载状态指示器 -->
            <view v-if="!item.loaded" class="absolute inset-0 flex items-center justify-center bg-gray-100">
              <text class="text-gray-500">加载中...</text>
            </view>
          </view>
        </nut-swiper-item>
      </nut-swiper>
    </view>

    <!-- 功能区域标题 -->
    <view
      class="section-title ml-[40rpx] mt-[50rpx] text-[35rpx] font-bold text-[#263238] flex items-center"
    >
      <text
        class="w-[10rpx] h-[44rpx] bg-[#2196F3] rounded-[6rpx] mr-[20rpx]"
      ></text>
      核心功能
    </view>

    <!-- 五大功能模块 -->
    <view
      class="features grid grid-cols-3 gap-[24rpx] px-[30rpx] mt-[20rpx] mb-[40rpx]"
    >
      <view
        @tap="handleFeatureClick(feature)"
        v-for="(feature, index) in features"
        :key="index"
        class="feature-card bg-white rounded-[32rpx] px-[16rpx] py-[36rpx] text-center shadow-[0_8rpx_24rpx_rgba(33,150,243,0.1)] transition-all duration-300 hover:translate-y-[-10rpx] hover:shadow-[0_16rpx_40rpx_rgba(33,150,243,0.2)] cursor-pointer"
      >
        <view
          class="feature-icon w-[100rpx] h-[100rpx] rounded-full mx-auto mb-[24rpx] flex items-center justify-center text-[48rpx] transition-all duration-300 hover:scale-110"
          :style="{ backgroundColor: feature.color }"
        >
          <IconFont
            font-class-name="iconfont"
            class-prefix="icon"
            :name="feature.icon"
            size="30"
            color="#ffffff"
          />
        </view>

        <text class="feature-title text-[28rpx] font-bold mb-[10rpx]">{{
          feature.title
        }}</text>
        <view class="feature-desc text-[24rpx] text-[#546E7A]">{{
          feature.desc
        }}</view>
      </view>
    </view>

    <!-- 项目展示测试区域 -->
    <!-- <view class="px-6 mt-6">
      <ProjectShowTest />
    </view> -->

    <!-- 悬赏任务区域 -->
    <view class="tasks-section px-[30rpx] mt-[50rpx] mb-[50rpx]">
      <view class="section-header flex justify-between items-center mb-[36rpx]">
        <text class="section-title text-[35rpx] font-bold text-[#263238]"
          >热门悬赏任务</text
        >
        <view
          class="view-all text-[30rpx] font-medium text-[#2196F3] flex items-center"
          @tap="viewAllTasks"
        >
          查看全部
          <IconFont name="right" class="ml-[10rpx]" size="12" />
          <!-- <icon-font name="angle-right" class="ml-[10rpx] transition-all duration-300 group-hover:text-[#1976D2] group-hover:translate-x-[6rpx]" /> -->
        </view>
      </view>

      <view class="tasks flex flex-col gap-[30rpx]">
        <view
          @tap="handleTaskClick(task)"
          v-for="task in allTask"
          :key="task.id"
          class="task-card bg-white rounded-[36rpx] p-[32rpx] flex shadow-[0_8rpx_30rpx_rgba(33,150,243,0.1)] transition-all duration-300 hover:translate-y-[-6rpx] hover:shadow-[0_16rpx_40rpx_rgba(33,150,243,0.2)] border-l-[8rpx] border-[#2196F3]"
        >
          <view
            class="task-icon w-[120rpx] h-[120rpx] rounded-[12rpx] bg-[#E3F2FD] flex items-center justify-center mr-[36rpx] text-[#2196F3] text-[48rpx]"
          >
            <!-- <IconFont
              :name="task.pic"
              font-class-name="iconfont"
              class-prefix="icon"
              class="text-[48rpx]"
              size="40"
            /> -->
            <image
              :src="getFullPath(task.avatar_url)"
              class="w-[90rpx] h-[90rpx] object-cover"
              @error="handleAvatarError"
            />
          </view>
          <view class="task-details flex-1">
            <text
              class="task-title font-bold text-[30rpx] text-[#263238] mb-[16rpx]"
              >{{ task.title }}</text
            >
            <text
              class="task-info text-[24rpx] text-[#546E7A] mb-[12rpx] block"
              >{{ task.describe_str }}</text
            >
            <text
              class="task-reward text-[32rpx] text-[#FF9800] font-bold mb-[12rpx]"
              >¥{{ task.total_amount }}</text
            >
            <!--<view class="task-tags flex gap-[12rpx] flex-wrap mt-[16rpx]">
              <text v-for="(tag, i) in task.tags" :key="i"
                    class="tag bg-[#E3F2FD] text-[#2196F3] text-[24rpx] px-[24rpx] py-[6rpx] rounded-[40rpx] font-medium"
                    :class="{ 'bg-[#FFF8E1] text-[#FF9800]': tag.highlight }">{{ tag.text }}
              </text>
            </view>-->
          </view>
        </view>
      </view>

      <!-- 4个板块 -->
      <view class="box-border px-[30rpx] pb-[120rpx]">
        <!-- <view class="section-title mb-[30rpx] text-[36rpx] font-bold text-[#263238]">平台服务</view> -->
        <nut-divider @click="navigateToDebugLogs">平台服务</nut-divider>
        <view class="nav-row grid grid-cols-2 gap-[24rpx] mt-[10rpx]">
          <view
            v-for="(item, index) in navItems"
            :key="index"
            class="nav-item flex flex-col items-center justify-center bg-white rounded-[32rpx] pt-[36rpx] pb-[30rpx] text-[30rpx] shadow-[0_8rpx_24rpx_rgba(33,150,243,0.1)] transition-all duration-300 cursor-pointer border border-[rgba(33,150,243,0.1)] hover:bg-gradient-to-r from-white to-[#E3F2FD] hover:translate-y-[-10rpx] hover:shadow-[0_16rpx_40rpx_rgba(33,150,243,0.2)]"
            @click="handleNavItem(item)"
          >
            <text
              class="nav-emoji text-[64rpx] transition-all duration-300 hover:scale-110"
              >{{ item.emoji }}</text
            >
            <text
              class="nav-text text-[30rpx] font-semibold text-[#2196F3] letter-spacing-[1rpx]"
              >{{ item.text }}
            </text>
          </view>
        </view>
      </view>
    </view>

  </view>

  <!-- 区域选择弹窗 -->
  <RegionPickerModal
    v-model:visible="showRegionPicker"
    mode="city"
    title="选择服务区域"
    @confirm="handleRegionConfirm"
    @cancel="handleRegionCancel"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import Taro, {useDidShow} from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import RegionPickerModal from "@/components/RegionPickerModal.vue";
// import SearchView from "@/components/SearchView.vue";
import { post } from "@/utils/request";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia"
import { onChangeTab } from "@/utils/hack";
import { getFullPath } from "@/utils/request";
import ren from "@/assets/pic/ren.png"
import ProjectShowTest from "@/components/ProjectShowTest.vue"


const userStore = useUserStore();
const {locationObj} = storeToRefs(userStore);

// 区域选择相关数据
const showRegionPicker = ref(false);

Taro.useDidShow(() => {
  onChangeTab('home')
})

const handleAvatarError = (event: any) => {
  event.target.src = ren;
};

const navigateToDebugLogs = () => {
  Taro.navigateTo({
    url: "/pages/webs/debug-logs",
  });
};

onMounted(() => {
  getBannerList();
  // currentBanner.value = bannerData[activeBannerIndex.value];
  const { params } = Taro.getCurrentInstance().router;
  console.log("params", params);
  const urlParams = new URLSearchParams(window.location.search);
  const rsd = urlParams.get('recommend');
  console.log("rsd", rsd);

  setTimeout(() => {
    const recommend = localStorage.getItem('recommend') || rsd;
    // Taro.showToast({
    //   title: "recommend:" + recommend,
    //   icon: "none",
    // });
    if (recommend) {
      post("/user/initRecommendCode", {
        recommendCode: recommend,
      }).then((res) => {
        console.log("res", res);
        localStorage.removeItem('recommend')
      });
    }
  }, 900);
})

// 位置信息
// const region = ref<[string | number, string | number]>(["", ""]);

// const onRegionChange = ({ province, city }) => {
//   // 处理选择结果
//   console.log(province, city);
//   region.value = [province.text, city.text];
// };

//定义任务获取的数据格式
interface taskColumn {
  describe_str: null;
  total_amount: null;
  name: null;
  memberName: null;
  memberStatus: null;
  id: null;
  pic: null;
  title: null;
  cycle: null;
  labels: null;
  status: null;
}

interface taskItem {
  columns: taskColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

//获取任务数据
const allTask = ref([]);

// 当前广告数据
const currentBanner = ref({ title: "", subtitle: "" });
const activeBannerIndex = ref(0);

// 广告内容数据
const bannerData = [
  {
    title: "新用户注册即送200元大礼包",
    subtitle: "海量优质工作机会，快速入职，薪资透明",
  },
  {
    title: "平台认证商家招募中",
    subtitle: "专属流量支持，快速招聘优质人才",
  },
  {
    title: "能力提升课程限时优惠",
    subtitle: "职业考证课程低至5折，名额有限",
  },
];

const bannerList= ref<any[]>([])

// 功能模块数据
const features = [
  {
    icon: "rijie",
    title: "日结区",
    desc: "订单制工作",
    color: "#f18f31",
    url: "/pages/webs/order-acceptance-square",
  },
  {
    icon: "list-fourliebiao",
    title: "悬赏区",
    desc: "任务制工作",
    color: "#42a6f9",
    url: "/pages/reward/hall",
  },
  {
    icon: "collection",
    title: "项目展示",
    desc: "展示优秀项目",
    color: "#b25ab9",
    url: "/pages/project-show/list",
  },
  {
    icon: "building",
    title: "工厂招聘",
    desc: "工厂招聘区",
    color: "#697dd4",
    url: "/pages/webs/factory-recruitment",
  },
  // {
  //   icon: "collection",
  //   title: "特殊招聘",
  //   desc: "高薪优质岗位",
  //   color: "#b25ab9",
  //   url: "/pages/webs/special-recruitment",
  // },
  {
    icon: "tisheng",
    title: "能力提升",
    desc: "职业考证/技能培训",
    color: "#49d56c",
    url: "/pages/webs/endless-learning-professional-online-learning-platform",
  },
  {
    icon: "qiandao",
    title: "签到区",
    desc: "定位签到",
    color: "#ff8f6b",
    url: "/pages/reward/signHall",
  },
];


// 导航项数据
const navItems = [
  { emoji: "🏪", text: "成为平台服务商", url: "/pages/webs/merchant-entry" },
  { emoji: "👨‍🏫", text: "成为平台从业者", url: "/pages/webs/personal-entry" },
  { emoji: "ℹ️", text: "信息", url: "/pages/message/message" },
  { emoji: "👋", text: "联系我们", url: "/pages/webs/contact-us" },
];


// 初始化广告
useDidShow(() => {
  // currentBanner.value = bannerData[activeBannerIndex.value];
  const { params } = Taro.getCurrentInstance().router;
  console.log("params", params);
  // setTimeout(() => {
  //   const recommend = localStorage.getItem('recommend') || params?.recommend
  //   if (recommend) {
  //     post("/user/initRecommendCode", {
  //       recommendCode: recommend,
  //     }).then((res) => {
  //       console.log("res", res);
  //     });
  //   }
  // }, 120);
  
  // startBannerRotation();
  // getBannerList();
});

const getBannerList = () => {
  post("/index/banner").then((res) => {
    console.log("banner API response:", res);
    if (res.data && Array.isArray(res.data)) {
      bannerList.value = res.data.map((item: any) => item.columns);
      console.log("处理后的 bannerList:", bannerList.value);
      console.log("轮播图数量:", bannerList.value.length);
    } else {
      console.warn("轮播图数据格式异常:", res.data);
      bannerList.value = [];
    }
  }).catch((error) => {
    console.error("获取轮播图失败:", error);
    bannerList.value = [];
  });

};

// 图片加载错误处理
const handleImageError = (e: any, index: number) => {
  console.error(`轮播图片 ${index} 加载失败:`, e);
  // 标记图片加载失败
  if (bannerList.value[index]) {
    bannerList.value[index].loaded = false;
    bannerList.value[index].error = true;
  }
};

// 图片加载成功处理
const handleImageLoad = (e: any, index: number) => {
  console.log(`轮播图片 ${index} 加载成功:`, e);
  // 标记图片加载成功
  if (bannerList.value[index]) {
    bannerList.value[index].loaded = true;
    bannerList.value[index].error = false;
  }
};

// 点击功能模块
const handleFeatureClick = (feature) => {
  // Taro.showToast({ title: `进入${feature.title}板块` });
  Taro.navigateTo({
    url: feature.url,
  });
};

const handleUserInfo = () => {
  Taro.navigateTo({
    url: "/pages/mine/mine",
  });
};

// 处理位置点击
const handleLocation = () => {
  showRegionPicker.value = true;
};

  // 处理区域选择确认
  const handleRegionConfirm = (result: any) => {
    if (result.province && result.city) {
      // 更新locationObj
      locationObj.value = {
        ...locationObj.value,
        address_component: {
          ...locationObj.value.address_component,
          province: result.province.name,
          city: result.city.name
        }
      };
      
      // 保存到缓存
      const userStore = useUserStore();
      userStore.saveLocationToCache();
      
      // 关闭弹窗
      showRegionPicker.value = false;
      
      Taro.showToast({
        title: `已选择：${result.province.name} ${result.city.name}`,
        icon: 'success'
      });

      getAllTask();
    }
  };

// 处理区域选择取消
const handleRegionCancel = () => {
  // 关闭弹窗
  showRegionPicker.value = false;
  
  Taro.showToast({
    title: '已取消选择',
    icon: 'none'
  });
};

// 查看所有任务
getAllTask();
function getAllTask() {
  //定义请求参数
  const submit = {
    pageNo: 1,
    pageSize: 4,
  };
  post("/task/all", submit).then((res) => {
    allTask.value = res.data.map((item: taskItem) => ({
      describe_str: item.columns.describe_str,
      total_amount: item.columns.total_amount,
      name: item.columns.name,
      memberName: item.columns.memberName,
      memberStatus: item.columns.memberStatus,
      id: item.columns.id,
      pic: item.columns.pic,
      title: item.columns.title,
      cycle: item.columns.cycle,
      labels: item.columns.labels,
      status: item.columns.status,
      avatar_url: item.columns.avatar_url,
    }));
  });
}

const viewAllTasks = () => {
  // Taro.showToast({ title: '即将跳转到任务列表页面' });
  Taro.navigateTo({
    url: "/pages/reward/hall",
  });
};

// 点击导航项
const handleNavItem = (item) => {
  // Taro.showToast({ title: `进入${item.text}页面` });
  Taro.navigateTo({
    url: item.url + '?status=' + userStore.userInfo.real_status,
  });
};

const handleTaskClick = (task) => {
  Taro.navigateTo({
    url: "/pages/webs/task-details-reward-task-platform?id=" + task.id,
  });
};

</script>

<style scoped>
/* 自定义轮播图指示器样式 */
:deep(.nut-swiper__pagination) {
  bottom: 20rpx !important;
}

:deep(.nut-swiper__pagination-item) {
  width: 12rpx !important;
  height: 12rpx !important;
  border-radius: 6rpx !important;
  margin: 0 6rpx !important;
  transition: all 0.3s ease !important;
}

:deep(.nut-swiper__pagination-item--active) {
  width: 40rpx !important; /* 20px = 40rpx */
  background-color: #426543 !important;
}

:deep(.nut-swiper__pagination-item:not(.nut-swiper__pagination-item--active)) {
  background-color: #808080 !important;
}
.task-info {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
